package First;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Send
 */
@WebServlet("/Send")
public class Send extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public Send() {
		// TODO Auto-generated constructor stub
	}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		response.setHeader("Access-Control-Allow-Origin", "*");
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String string = " 22:00:00"; // 定时为每天晚上十点提醒
		Date date = null;
		String time=null;
		Calendar now = Calendar.getInstance();  
		int year=now.get(Calendar.YEAR);
		int month=now.get(Calendar.MONTH) + 1;
		int day=now.get(Calendar.DAY_OF_MONTH);
		if(day<10){
			time="0"+day;
		}else{
			time=day+"";
		}
		if(month<10){
			time=year+"-0"+month+"-"+time;
		}else{
			time=year+"-"+month+"-"+time;
		}
		string=time+string;
		//System.out.println("今天发送的时间"+string);
		try {
			date = sf.parse(string);
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Timer timer = new Timer();
		timer.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				Map<String, String> map = OntimeSend.emailtipmap();
				String to = "";
				String tip = "";
				for (Map.Entry<String, String> entry : map.entrySet()) {
					to = entry.getKey();
					tip = entry.getValue();
					//System.out.println("to=" + to + " tip=" + tip);
					try {
						System.out.println("to="+to+" tip="+tip);
						OntimeSend.sendMail(to, tip);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					// System.out.println("发送邮箱成功！");
				}
			}
		}, date, 24*3600*1000);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html; charset=utf-8");
		request.setCharacterEncoding("utf-8");
		doGet(request, response);
	}
	
}
